package com.example.myapplication.ui.components


import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.Canvas
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke

@Composable
fun ChartView( points: List<Int>, modifier: Modifier = Modifier) {

    // 每一行高度
    val heightForRow = 24

    // 总行数
    val countForRow = 5

    val perY = 8 // 24 * 5 / 15, 每8dp代表1积分,每一行3积分

    // 圆圈半径
    // 高度需要附加小圆圈半径,如果不加的话当小圆圈在最顶上会被遮住显示不出来
    val circleRadius = 2.5

    // canvas宽度: 使用屏幕宽度减去padding * 2
    val canvasWidth = LocalConfiguration.current.screenWidthDp - 8 * 2

    // canvas高度: 行高 * 总行数
    val canvasHeight = heightForRow * countForRow + circleRadius * 2

    // 7平分宽度
    val averageOfWidth = canvasWidth / 7

    Canvas(modifier = modifier.size(width = canvasWidth.dp, height = canvasHeight.dp)) {
        // 背景横线
        for (index in 0..countForRow) {
            // 每条横线的位置,canvas中使用的px,需要提前转换
            val startY = (heightForRow * index + circleRadius).dp.toPx()
            drawLine(
                Color(0xffeeeeee),
                start = Offset(0f, startY),
                end = Offset(size.width, startY),
                strokeWidth = 2.5f
            )
        }

        // 圆圈/折线
        // until 左闭右开
        for (index in 0 until points.count()) {
            // circleCenter 圆圈圆心, 每列宽度 * 个数 + 每列宽度的一半(第一个圆到边缘的距离)
            val circleCenter = Offset(
                (averageOfWidth * index + averageOfWidth / 2).dp.toPx(),
                (heightForRow * countForRow - points[index] * perY + circleRadius).dp.toPx()
            )
            // Stroke 画圈
            drawCircle(
                Color(0xff149ee7),
                radius = circleRadius.dp.toPx(),
                center = circleCenter,
                style = Stroke(5f)
            )

            // 画线
            // 最后一条线不画(七个点六条线)
            if (index < points.count() - 1) {
                // 下一个圆圈圆心
                val nextPoint = Offset(
                    (averageOfWidth * (index + 1) + averageOfWidth / 2).dp.toPx(),
                    (heightForRow * countForRow - points[index + 1] * perY + circleRadius).dp.toPx()
                )
                drawLine(Color(0xff149ee7), start = circleCenter, end = nextPoint, strokeWidth = 5f)
            }
        }
    }
}


